import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QPushButton, QTableWidget, \
    QTableWidgetItem, QHeaderView, QMainWindow, QMessageBox, QDialog
from ledger import GiftLedger
from dialogs import AddRecordDialog, EditRecordDialog, LedgerSelectorDialog
from chart import PieChart
import logging

# 配置日志记录
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')


class GiftManagerApp(QWidget):
    def __init__(self, ledger_type):
        super().__init__()
        self.setWindowTitle("人情礼簿管理系统")
        self.setGeometry(100, 100, 800, 600)

        self.send_ledger = GiftLedger("send")
        self.receive_ledger = GiftLedger("receive")
        self.current_ledger = self.send_ledger if ledger_type == "send" else self.receive_ledger
        self.stats_window = None
        self.chart = None

        self.initUI()
        self.create_toolbar()
        self.refresh_table()

    def initUI(self):
        layout = QVBoxLayout()

        self.toolbar = QHBoxLayout()
        layout.addLayout(self.toolbar)

        self.table = QTableWidget()
        self.table.setColumnCount(7)
        self.table.setHorizontalHeaderLabels(['ID', '姓名', '金额', '日期', '关系', '场合', '备注'])
        self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeToContents)
        layout.addWidget(self.table)

        # 添加返回按钮
        back_button = QPushButton("返回选择账本")
        back_button.clicked.connect(self.return_to_ledger_selection)
        layout.addWidget(back_button)

        self.setLayout(layout)

    def create_toolbar(self):
        for i in reversed(range(self.toolbar.count())):
            self.toolbar.itemAt(i).widget().setParent(None)

        add_button = QPushButton("添加记录")
        add_button.clicked.connect(self.add_record)
        self.toolbar.addWidget(add_button)

        refresh_button = QPushButton("刷新数据")
        refresh_button.clicked.connect(self.refresh_table)
        self.toolbar.addWidget(refresh_button)

        stats_button = QPushButton("统计图表")
        stats_button.clicked.connect(self.show_stats)
        self.toolbar.addWidget(stats_button)

    def refresh_table(self):
        self.table.setRowCount(0)
        for record in self.current_ledger.get_records():
            row_position = self.table.rowCount()
            self.table.insertRow(row_position)
            self.table.setItem(row_position, 0, QTableWidgetItem(str(record['id'])))
            self.table.setItem(row_position, 1, QTableWidgetItem(record['name']))
            self.table.setItem(row_position, 2, QTableWidgetItem(f"￥{record['amount']}"))
            self.table.setItem(row_position, 3, QTableWidgetItem(record['date']))
            self.table.setItem(row_position, 4, QTableWidgetItem(record.get('relationship', '')))
            self.table.setItem(row_position, 5, QTableWidgetItem(record.get('occasion', '')))
            self.table.setItem(row_position, 6, QTableWidgetItem(record.get('notes', '')))
        logging.info("Refreshed the table")

    def add_record(self):
        dialog = AddRecordDialog(self, self.current_ledger, self.refresh_table, self.update_stats)
        dialog.exec_()

    def edit_selected(self):
        selected_items = self.table.selectedItems()
        if not selected_items:
            return

        record_id = int(selected_items[0].text())
        dialog = EditRecordDialog(self, self.current_ledger, self.refresh_table, self.update_stats, record_id)
        dialog.exec_()

    def delete_selected(self):
        selected_items = self.table.selectedItems()
        if not selected_items:
            return

        record_id = int(selected_items[0].text())
        reply = QMessageBox.question(self, "确认删除", "确定要删除这条记录吗？", QMessageBox.Yes | QMessageBox.No)
        if reply == QMessageBox.Yes:
            self.current_ledger.delete_record(record_id)
            self.refresh_table()
            self.update_stats()
            logging.info(f"Confirmed to delete record with ID {record_id}")

    def show_stats(self):
        if self.stats_window is not None:
            self.stats_window.close()

        self.stats_window = QMainWindow()
        self.stats_window.setWindowTitle("统计信息")
        self.stats_window.setGeometry(400, 400, 600, 400)

        central_widget = QWidget()
        layout = QVBoxLayout()

        # 创建 matplotlib 图形和画布
        self.chart = PieChart(self.stats_window)
        self.chart.create_chart()
        layout.addWidget(self.chart.canvas)

        back_button = QPushButton("返回")
        back_button.clicked.connect(self.stats_window.close)
        layout.addWidget(back_button)

        central_widget.setLayout(layout)
        self.stats_window.setCentralWidget(central_widget)

        self.update_stats()
        self.stats_window.show()

    def update_stats(self):
        if self.chart:
            self.chart.update_chart(self.send_ledger, self.receive_ledger)

    def return_to_ledger_selection(self):
        self.close()
        selector_dialog = LedgerSelectorDialog()
        if selector_dialog.exec_() == QDialog.Accepted:
            selected_ledger = selector_dialog.selected_ledger
            self.current_ledger = self.send_ledger if selected_ledger == "send" else self.receive_ledger
            self.refresh_table()
            self.show()


if __name__ == "__main__":
    app = QApplication(sys.argv)
    selector_dialog = LedgerSelectorDialog()
    if selector_dialog.exec_() == QDialog.Accepted:
        selected_ledger = selector_dialog.selected_ledger   
        ex = GiftManagerApp(selected_ledger)
        ex.show()
    sys.exit(app.exec_())